const { Comment, User, Thumbs } = require("../model");

// 改
exports.updateRole = async (req, res, next) => {
  try {
    const fun = await Comment.findByIdAndUpdate(req.params.id, {
      $set: req.body
    })
    if (fun) {
      res.status(200).json({
        code: 200,
        msg: "success",
      });
    } else {
      res.status(200).json({
        code: 500,
        msg: "修改失败",
      });
    }
    
  } catch (error) {
    next(error);
  }
};

// 查
exports.getRole = async (req, res, next) => {
  try {
    console.log('getRole', req.body)
    // 模糊查询
    let where = {};
    if (req.body.funId) {
      where.funId = req.body.funId
    }
    if (req.body.userId) {
      where.userId = req.body.userId
    }
    const items = await Comment.find(where);
    let data = []
    for (let i = 0;i< items.length;i++) {
      // 查询评论的发表用户信息
      let user = await User.find({
        _id: items[i].userId
      });
      // 查询评论的点赞信息
      let thumbs = await Thumbs.find({
        commentId: items[i]._id
      })
      data.push({
        comment: items[i],
        userInfo: user,
        thumbs
      })
    }
    res.status(200).json({
      code: 200,
      data
    });
  } catch (error) {
    next(error);
  }
};
// 增
exports.addRole = async (req, res, next) => {
  try {
    const model = new Comment(req.body);
    await model.save();
    res.status(200).json({
      code: 200,
      msg: "success",
    });
  } catch (error) {
    next(error);
  }
};
// 删
exports.deleteRole = async (req, res, next) => {
  try {
    const rs = await Comment.findByIdAndDelete(req.params.id)
    if (rs) {
      res.status(200).json({
        code: 200,
        msg: '删除成功'
      });
    }
  } catch (error) {
    next(error);
  }
};

